import { VideoPlayer, Button, ButtonGroup, Image } from '@douyinfe/semi-ui';
import { Message } from '@arco-design/web-react';
import { forwardRef, useEffect, useCallback, useState } from 'react';
import deleteIcon from '@/assets/images/imageEdit/delete.svg';
import download from '@/assets/images/imageEdit/download.svg';
import copy from '@/assets/images/imageEdit/copy.svg';
import styles from './resultList.module.scss';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';
import { useLoading } from '@/components/common/mlsLoading/laodingText';
import { synthesisHistoryListGet, synthesisHistoryListDelete } from '@/api/common.jsx';
import { downloadMedia } from '@/utils/common.jsx';

const Results = forwardRef(({ resultsItemRefs, currentMenuTitle, passVideoHistoryList }, ref) => {
  const [videoHistoryList, setVideoHistoryList] = useState([]);
  const { showLoading, hideLoading } = useLoading();

  const BTN_TYPE = [
    {
      type: 'downlaod',
      icon: download,
      text: '下载',
    },
    {
      type: 'delete',
      icon: deleteIcon,
      text: '删除',
    },
  ];
  const DURATION_OPTIONS = [
    {
      label: '5s',
      value: 'short',
    },
    {
      label: '10s',
      value: 'long',
    },
  ];

  const fetchVedioList = useCallback(async () => {
    showLoading('加载中...'); // 显示加载状态
    const res = await synthesisHistoryListGet({
      operType: 'textToVideo',
    });
    if (res?.code === 200) {
      let list = (res?.data?.list || []).map(item => {
        let obj = item.operInfo ? JSON.parse(item.operInfo) : {};
        return {
          ...item,
          videoUrl: item.fileUrl,
          duration: obj.duration ? DURATION_OPTIONS[obj.duration] : '',
          apiName: obj.apiName || '',
          ratio: obj.ratio || '',
          resolution: obj.resolution || '',
          text: obj.text || '',
          firstFrameUrl: obj.firstFrameUrl || '',
        };
      });
      setVideoHistoryList(list);
      passVideoHistoryList(list);
    }
    hideLoading(); // 隐藏加载状态
  }, [hideLoading, passVideoHistoryList, passVideoHistoryList]);

  const handleOptClick = useCallback(
    (type, item) => {
      if (type === 'delete') {
        synthesisHistoryListDelete({
          historyId: item.historyId,
        }).then(res => {
          if (res?.code === 200) {
            Message.success('删除成功');
            fetchVedioList();
          }
        });
      } else if (type === 'downlaod') {
        console.log('downloadMedia', item.videoUrl);
        downloadMedia(item.videoUrl);
      }
    },
    [fetchVedioList, downloadMedia]
  );

  useEffect(() => {
    fetchVedioList();
  }, [fetchVedioList]);

  useEffect(() => {
    const handleOpt = data => {
      console.log('socket---', data);
      if (data?.func === 'text_to_video_success') {
        // 再去查询列表
        hideLoading();
        fetchVedioList();
      }
      if (data?.func === 'text_to_video_fail') {
        hideLoading();
        Message.error('生成失败');
      }
    };

    sharedWebSocket.on('resp', handleOpt);
    return () => {
      sharedWebSocket.off('resp', handleOpt);
    };
  }, [hideLoading]);

  return (
    <div className={styles.results} ref={ref}>
      {videoHistoryList.map((item, index) => (
        <div
          key={index}
          className={styles.resultsItem}
          ref={el => (resultsItemRefs.current[index] = el)}>
          <div className={styles.resultsHead}>
            <div className={styles.resultsHeadLeft}>
              <div className={styles.resultsHeadTitle}>{item.title || '文生视频'}</div>
              <div className={styles.separate}></div>
              <div className={styles.resultsHeadText}>
                <div className={styles.tabText}>{item.apiName}</div>
                <div className={styles.tabText}>{item.resolution}</div>
                <div className={styles.tabText}>{item.ratio}</div>
                {/* {currentMenuKey=='pic'&&<div className={styles.thumbnail}>
                  <Image className={styles.img} src={''} preview={false} draggable={false} />
                  <span>参考图</span>
                </div>} */}
              </div>
            </div>
            {/* <div className={styles.resultsHeadTime}>{item.time}</div> */}
          </div>
          <div className={styles.resultsContent}>
            {item.text}
            <Image className={styles.img} src={copy} preview={false} draggable={false} />
          </div>

          <VideoPlayer
            height={630}
            src={item.videoUrl}
            poster={item.firstFrameUrl}
            controlsList={['play', 'time', 'fullscreen']}
          />

          <div className={styles.resultsOptBtns}>
            {BTN_TYPE.map(sub => (
              <div className={styles.btnBox} key={sub.type}>
                <Button
                  style={{ fontWeight: 400, color: '#fff', opacity: 0.8 }}
                  onClick={() => handleOptClick(sub.type, item)}
                  icon={
                    <>
                      <Image
                        className={styles.img}
                        src={sub.icon}
                        preview={false}
                        draggable={false}
                      />
                    </>
                  }
                  type={'tertiary'}>
                  {sub.text}
                </Button>
              </div>
            ))}
          </div>
        </div>
      ))}
    </div>
  );
});

Results.displayName = 'Results';

export default Results;
